<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\ask\XhaskSurvey;
use Admin\Models\user\UserOnline;
use Helpers\Hrm;
use Helpers\CaptchaImage;
use Helpers\Session;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Assets;
use Helpers\User;
use Helpers\UserPower;
use Admin\Models\sys\XhsysTree;
use Admin\Models\user\XhsysUser;
use Services\Login\Login;
use Services\Sys\ValidCode;

class IndexController extends ControllerBase
{

    /**
     * 登录页面
     *
     * create by ck 20160229
     * modify by ck 20170907    添加backUrl参数
     * modify by ck 20180416    记住密码则自动填充账号密码
     * modify by ck 20180628    信任设备
     */
    public function loginAction()
    {
        //判断是否已经登陆，否则跳转到主页面
        if (User::isLogin()) {
            return $this->response->redirect($this->request->getQuery('backUrl', 'string'));
        }
        if ($this->request->isAjax()) {
            return $this->sendErrorResponse(401, '未登录，不可操作');
        }
        $this->tag->setTitle('登陆');
        $this->view->pick('index/login');
        Assets::importMainJs('assets/particles/particles.min.js');
//        Assets::importMainCss('assets/animated-mesh-line/vendors.css');
//        Assets::importMainJs('assets/animated-mesh-line/vendors.js');
//        Assets::importMainCss('assets/animated-mesh-line/demo2.css');
//        Assets::importMainJs('assets/animated-mesh-line/demo2.js');
        Assets::toast('js/index/login.js');
        $viewArr = [
            'remember'  => false,
            'trust'     => $this->cookies->has('trustLogin'),
        ];
        $viewArr['trustAccount'] = $viewArr['trust']
            ? $this->crypt->decryptBase64($this->cookies->get('trustLogin')->getValue())
            : '';
        if ($this->cookies->has('autoLogin')) {
            $autoLogin = json_decode($this->crypt->decryptBase64($this->cookies->get('autoLogin')->getValue()), true);
            $this->tag->setDefaults($autoLogin);
            $viewArr['remember'] = true;
        }
        return $this->view->setVars($viewArr);
    }

    /**
     * 是否信任
     *
     * @param $account
     * @return bool
     *
     * create by ck 20190114
     */
    private function isTrust($account)
    {
        $trustLogin = $this->crypt->decryptBase64($this->cookies->get('trustLogin')->getValue());
        return $trustLogin == $account;
    }

    /**
     * 登陆
     *
     * create by ck 20160229
     * modify by ck 20160617
     * modify by ck 20170503    添加cookie
     * modify by ck 20170831    更改逻辑
     * modify by ck 20180330    添加验证码判断
     * modify by ck 20180402    员工则判断密码复杂度
     * modify by ck 20180410    超级管理员且有手机号则需短信验证
     * modify by ck 20180416    记住密码且符合同一账号则跳过验证码，记录cookie
     * modify by ck 20180628    信任设备
     * modify by ck 20190114    重构
     */
    public function loginInAction()
    {
        $account  = $this->request->getPost('account', 'string');
        $password = $this->request->getPost('password', 'string');
        $captcha  = $this->request->getPost('captcha', 'string');
        $smsCode  = $this->request->getPost('smsCode', 'string');
        $remember = $this->request->getPost('remember', 'string') == 'true';
        $trust    = $this->request->getPost('trust', 'string') == 'true';
        if (!$account) {
            return $this->sendErrorResponse(400, '账号不能为空');
        }
        if (!$password) {
            return $this->sendErrorResponse(400, '密码不能为空');
        }
        try {
            //判断是否信任，信任则直接执行登陆
            if (!$this->isTrust($account)) {
                $needValid = Login::needValidCode($account);
                if ($needValid) {
                    //判断短信验证码
                    if (!$smsCode) {
                        return $this->sendErrorResponse(401, '需要短信验证');
                    }
                    if (!Login::checkValidCode($account, $smsCode)) {
                        throw new \Exception('短信验证码错误');
                    }
                } else {
                    //判断图形验证码
                    if (!$captcha) {
                        return $this->sendErrorResponse(402, '需输入图形验证码');
                    }
                    if ($captcha != Session::get('loginCaptcha')) {
                        return $this->sendErrorResponse(400, '验证码不正确');
                    }
                }
            }

            Session::remove('loginCaptcha');
            Login::doLogin($account, $password);

            //检查员工密码复杂度(仅数字及位数)
            if (User::isStaff() && (is_numeric($password) || strlen($password) < 8)) {
                Session::set('changePwd', true);
            }

            //处理记住密码
            if ($remember) {
                $this->cookies->set('autoLogin', $this->crypt->encryptBase64(json_encode([
                    'account' => $account,
                    'password' => $password
                ])), time() + 3600 * 24 * 365);
            } else {
                $this->cookies->get('autoLogin')->delete();
            }

            //处理信任
            if ($trust) {
                $this->cookies->set('trustLogin', $this->crypt->encryptBase64($account), time() + 3600 * 24 * 365);
            } else {
                $this->cookies->get('trustLogin')->delete();
            }

            return $this->sendSuccessResponse('登陆成功', !User::isAdmin());
        } catch (\Exception $e) {
            $this->cookies->get('trustLogin')->delete();
            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
        }
    }

    /**
     * 判断用户名密码是否正确，正确后将ID，用户名，登录名储存在session中
     *
     * create by ck 20160229
     * modify by ck 20160617
     * modify by ck 20170503    添加cookie
     * modify by ck 20170831    更改逻辑
     * modify by ck 20180330    添加验证码判断
     * modify by ck 20180402    员工则判断密码复杂度
     * modify by ck 20180410    超级管理员且有手机号则需短信验证
     * modify by ck 20180416    记住密码且符合同一账号则跳过验证码，记录cookie
     * modify by ck 20180628    信任设备
     */
//    public function loginInAction()
//    {
//        $account  = $this->request->getPost('account', 'string');
//        $password = $this->request->getPost('password', 'string');
//        $captcha  = $this->request->getPost('captcha', 'string');
//        $smsCode  = $this->request->getPost('smsCode', 'string');
//        $remember = $this->request->getPost('remember', 'string') == 'true';
//        $trust    = $this->request->getPost('trust', 'string') == 'true';
//        if (!$account) {
//            return $this->sendErrorResponse(400, '账号不能为空');
//        }
//        if (!$smsCode && !$password) {
//            return $this->sendErrorResponse(400, '密码不能为空');
//        }
//        try {
//            //若非信任，无短信验证码则判断图形验证码
//            $trustLogin = $this->crypt->decryptBase64($this->cookies->get('trustLogin')->getValue());
//            $isTrust = $trustLogin == $account;
//            if (!$isTrust && !$smsCode) {
//                if (!$captcha) {
//                    return $this->sendErrorResponse(402, '需输入图形验证码');
//                }
//                if ($captcha != Session::get('loginCaptcha')) {
//                    return $this->sendErrorResponse(400, '验证码不正确');
//                }
//            }
//
//            //判断记住密码账号是否匹配，图形验证码赋值
////            if ($this->cookies->has('autoLogin')) {
////                $autoLogin = json_decode($this->crypt->decryptBase64($this->cookies->get('autoLogin')->getValue()), true);
////                if ($autoLogin['account'] == $account) {
////                    $captcha = $this->session->get('loginCaptcha');
////                }
////            }
//            //图形验证码不匹配，且之前为记住密码（未输入图形验证码），提示需输入图形验证码
////            if (!$smsCode && $captcha != $this->session->get('loginCaptcha')) {
////                if ($this->cookies->has('autoLogin')) {
////                    return $this->sendErrorResponse(402, '需输入图形验证码');
////                }
////                return $this->sendErrorResponse(400, '验证码不正确');
////            }
//
//            //超级管理员则判断短信验证码
////            if ($account == 'admin' && !$smsCode) {
////                $phone = Main::getConfigByName('admin')['phone'];
////                if ($phone) {
////                    return $this->sendErrorResponse(401, '需验证手机并输入短信验证码');
////                }
////            }
//
//            Session::remove('loginCaptcha');
////            $this->session->remove('loginCaptcha');
//            User::login($account, $password, $smsCode, $isTrust);
//
//            //检查员工密码复杂度(仅数字及位数)
//            if (User::isStaff() && (is_numeric($password) || strlen($password) < 8)) {
//                Session::set('changePwd', true);
////                $this->session->set('changePwd', true);
//            }
//
//            //处理记住密码
//            if ($remember) {
//                $this->cookies->set('autoLogin', $this->crypt->encryptBase64(json_encode([
//                    'account' => $account,
//                    'password' => $password
//                ])), time() + 3600 * 24 * 365);
//            } else {
//                $this->cookies->get('autoLogin')->delete();
////                $this->cookies->set('autoLogin', '', time() - 3600);
//            }
//
//            //处理信任
//            if ($trust) {
//                $this->cookies->set('trustLogin', $this->crypt->encryptBase64($account), time() + 3600 * 24 * 365);
//            } else {
//                $this->cookies->get('trustLogin')->delete();
//            }
//
//            return $this->sendSuccessResponse('登陆成功', !User::isAdmin());
//        } catch (\Exception $e) {
//            $this->cookies->get('trustLogin')->delete();
//            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
//        }
//    }

    /**
     * 生成验证码，写入session
     *
     * create by ck 20180330
     */
    public function captchaImageAction()
    {
        $this->view->disable();
        $code = Tool::getRand(4);
        Session::set('loginCaptcha', $code);
        $captcha = new CaptchaImage($code);
        $captcha->imageOut();
//        Tool::createCaptchaImage($code);
    }

    /**
     * 检查是否需要短信验证码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180428
     * modify by ck 20180628    判断是否信任
     * modify by ck 20181029    发送短信验证码条件判断all
     * modify by ck 20190114    使用Login类
     */
    public function checkNeedValidAction()
    {
        $account = $this->request->getPost('account', 'string');
        if (!$account) {
            return $this->sendErrorResponse(400, '账号不能为空', '', false);
        }

        //判断是否信任
        $trustLogin = $this->crypt->decryptBase64($this->cookies->get('trustLogin')->getValue());
        if ($trustLogin == $account) {
            return $this->sendErrorResponse(400, '无需发送短信', '', false);
        }

        return Login::needValidCode($account)
            ? $this->sendSuccessResponse('需发送短信', false)
            : $this->sendErrorResponse(400, '无需发送短信', '', false);

//        $sysConfig = Main::getConfigByName('admin');
//
//        //判断是否需要发送验证码登陆
//        if ($account == 'admin') {
//            $phone = Tool::getValue($sysConfig, 'phone');
//            if ($phone) {
//                return $this->sendSuccessResponse('需发送短信', false);
//            }
//        } else {
//            $user = $this->modelsManager->createBuilder()
//                ->columns(['u.iUserId', 'u.sLogonName', 'u.sUserName', 'u.iUserType', 'u.sLogonPwd', 'u.sSelfPhone', 'u.iSchoolId'])
//                ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
//                ->leftJoin('\\Admin\\Models\\hrm\\XhhrmStaff', 'u.iUserId = s.iUserId AND s.bDelete = 0', 's')
//                ->where('u.bDelete = 0 AND u.bDisable = 0')
//                ->andWhere('u.sLogonName = :account: OR u.sSelfPhone = :account:', ['account' => $account])
//                ->orderBy('s.iStaffId DESC,u.iUserId ASC')
//                ->limit(1)
//                ->getQuery()->execute()->toArray();
//            if (!$user) {
//                return $this->sendErrorResponse(400, '无该账号', '', false);
//            }
//            $user = $user[0];
//
//            try {
//                $depInfo = Hrm::getDepInfoByUser($user['iUserId']);
//            } catch (\Exception $e) {
//                $depInfo = [];
//            }
//            $needSmsCodeDep = Tool::getValue($sysConfig, 'needSmsCodeDep', [], function ($value) {
//                return array_filter(explode('|', $value));
//            });
//            $checkDep = array_intersect($needSmsCodeDep, array_column($depInfo, 'tag'))
//                || $needSmsCodeDep[0] == 'all';
//            if ($checkDep && $user['sSelfPhone']) {
//                return $this->sendSuccessResponse('需发送短信', false);
//            }
//        }
//        return $this->sendErrorResponse(400, '无需发送短信', '', false);
    }

    /**
     * 获取手机验证码登陆
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180410
     * modify by ck 20180418    添加用户手机判断
     * modify by ck 20190115    重构
     */
    public function getLoginSmsCodeAction()
    {
        $account = trim($this->request->getPost('account', 'string'));
        $phone   = trim($this->request->getPost('phone', 'string'));
        if (!$account) {
            return $this->sendErrorResponse(400, '账号不能为空');
        }
        if (!$phone) {
            return $this->sendErrorResponse(400, '手机号不能为空');
        }
        try {
            $userPhone = Login::getPhoneByAccount($account);
//            if ($account == 'admin') {
//                $userPhone = Main::getConfigByName('admin')['phone'];
//            } else {
//                $user      = XhsysUser::findFirst([
//                    'columns'    => 'sSelfPhone',
//                    'conditions' => 'bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND (sLogonName = :account: OR sSelfPhone = :account:) AND sSelfPhone = :phone:',
//                    'bind'       => ['account' => $account, 'phone' => $phone]
//                ]);
//                $userPhone = $user ? $user->sSelfPhone : '';
//            }
            if ($phone != $userPhone) {
                return $this->sendErrorResponse(400, '手机号与账号不匹配');
            }
            ValidCode::send($phone, null, 'login', 'doLogin', ValidCode::TYPE_LOGIN);
//            Main::sendValidCode($phone, Tool::getRand(6), 'admin', 'login');
            return $this->sendSuccessResponse('短信发送成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改密码
     *
     * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180402
     * modify by ck 20181204    不可手动进入
     */
    public function passwordAction()
    {
        if (!User::isLogin() || !Session::has('changePwd')) {
            return $this->response->redirect();
        }
        $this->tag->setTitle('密码修改');
        $this->view->pick('index/password');
        $this->flash->warning('密码过于简单，请修改密码');
        Assets::importMainJs('assets/particles/particles.min.js');
        Assets::toast('js/index/password.js');
        return true;
    }

    /**
     * 发送验证码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180402
     * modify by ck 20190115    重构
     */
    public function getValidCodeAction()
    {
        if (!User::isLogin()) {
            return $this->sendErrorResponse(400, '未登录');
        }
        try {
            $phoneNum = Login::getInfo()->phone;
//            $phoneNum = XhhrmStaff::getPhoneById([User::getId()])[User::getId()];
            if (!$phoneNum) {
                return $this->sendErrorResponse(500, '找不到手机号');
            }
            ValidCode::send($phoneNum, null, 'login', 'simplePwd', ValidCode::TYPE_CHANGE_PWD);
//            Main::sendValidCode($phoneNum, null, 'admin', 'login');
            return $this->sendSuccessResponse('验证码发送成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180402
     * modify by ck 20190115    重构
     */
    public function savePasswordAction()
    {
        if (!User::isLogin()) {
            return $this->sendErrorResponse(400, '未登录');
        }
        $password = $this->request->getPost('password', 'string');
        $captcha  = $this->request->getPost('captcha', 'string');
        if (!$password || !$captcha) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if (is_numeric($password) || strlen($password) < 8) {
            return $this->sendErrorResponse(400, '密码至少8位，且不能为纯数字');
        }
        try {
            $phoneNum = Login::getInfo()->phone;
//            $phoneNum = XhhrmStaff::getPhoneById([User::getId()])[User::getId()];
            if (!$phoneNum) {
                throw new \Exception('找不到手机号');
            }
            if (!ValidCode::check($phoneNum, $captcha, ValidCode::TYPE_CHANGE_PWD)) {
//            if (!Main::checkValidCode($phoneNum, $captcha)) {
                throw new \Exception('验证码错误或已失效');
            }
            User::setPassword(User::getId(), $password);
            Session::remove('changePwd');
            return $this->sendSuccessResponse('密码修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 找回密码
     *
     * @return bool
     *
     * create by ck 20180623
     */
    public function forgetPasswordAction()
    {
        $this->tag->setTitle('找回密码');
        $this->view->pick('index/forgetPassword');
        Assets::importMainJs('assets/particles/particles.min.js');
        Assets::toast('js/index/forgetPassword.js');
        return true;
    }

    /**
     * 发送验证码-找回密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180623
     */
    public function sendCodeForForgetPasswordAction()
    {
        $phone = $this->request->getPost('phone', 'string');
        if (!$phone) {
            return $this->sendErrorResponse(400, '缺少手机号');
        }
        try {
            $user = XhsysUser::findFirst([
                'columns'    => 'sSelfPhone',
                'conditions' => 'bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND sSelfPhone = :phone:',
                'bind'       => ['phone' => $phone]
            ]);
            if (!$user) {
                return $this->sendErrorResponse(400, '该手机号无对应用户');
            }
            ValidCode::send($phone, null, 'login', 'forgetPwd', ValidCode::TYPE_CHANGE_PWD);
//            Main::sendValidCode($phone, Tool::getRand(6), 'admin', 'forgetPassword');
            return $this->sendSuccessResponse('短信发送成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180623
     */
    public function changePasswordByCodeAction()
    {
        $phone      = $this->request->getPost('phone', 'string');
        $code       = $this->request->getPost('code', 'string');
        $password   = $this->request->getPost('password', 'string');
        if (!$phone || !$code || !$password) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        if (is_numeric($password) || strlen($password) < 8) {
            return $this->sendErrorResponse(400, '密码至少8位，且不能为纯数字');
        }
        try {
//            if (!Main::checkValidCode($phone, $code)) {
            if (!ValidCode::check($phone, $code, ValidCode::TYPE_CHANGE_PWD)) {
                throw new \Exception('验证码错误或已失效');
            }
            $user = XhsysUser::findFirst([
                'columns'    => 'iUserId',
                'conditions' => 'bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND sSelfPhone = :phone:',
                'bind'       => ['phone' => $phone]
            ]);
            if (!$user) {
                throw new \Exception('该手机号无对应用户');
            }
            User::setPassword($user->iUserId, $password);
            //百分邮箱修改
//            $staff = XhhrmStaff::findFirst([
//                'columns'    => 'sHundredMail',
//                'conditions' => 'bDelete = 0 and iUserId =:iUserId:',
//                'bind'       => ['iUserId' => $user->iUserId]
//            ]);
//            if ($staff) {
//                if ($staff->sHundredMail) {
//                    $res = HundredMail::modifyMailPassword($staff->sHundredMail, $password);
//                    if ($res) {
//                        return $this->sendSuccessResponse('修改成功,已同步更新百分邮箱密码');
//                    }
//                }
//            }
            return $this->sendSuccessResponse('修改成功');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 基础页面
     *
     * create by ck 20160229
     * modify by ck 20160914    压缩js文件
     * modify by ck 20160929    优化assets输出
     * modify by ck 20151013    js不压缩
     * modify by ck 20180402    添加是否需要跳转到修改密码页面
     */
    public function indexAction()
    {
        try {
            $this->view->pick('index/index');
            $this->tag->setTitle('后台管理系统');
            if (!User::isLogin()) {
                $this->dispatcher->forward([
                    'controller' => 'index',
                    'action'     => 'login',
                ]);
                return false;
            }
            //需要跳转则跳转
            if ($this->session->has('changePwd')) {
                $this->dispatcher->forward([
                    'controller' => 'index',
                    'action'     => 'password',
                ]);
                return false;
            }
            $this->assets
//                ->addCss('assets/easyui/themes/metro/tabs.css')
//                ->addCss('assets/easyui/themes/metro/menu.css')
                ->addCss('assets/sweetalert2/sweetalert2.min.css');
            $this->assets
                ->addJs('assets/jquery/jquery.slimscroll.min.js', true, false)
                ->addJs('assets/easyui/jquery.easyui.min.js', true, false)
                ->addJs('assets/jquery/jquery.md5.js', true, false)
                ->addJs('assets/sweetalert2/sweetalert2.min.js');
            Assets::nthTabs();
            Assets::importMainJs('assets/xh/xhTop.js');
            Assets::importJs('js/index/simplify.js');
            Assets::importJs('js/index/index.js');
            Assets::importJs('js/remind/msg.js');
            return $this->view->setVars(array(
                'UserName'  => Main::getLoginUserInfo('userName'),
                'isStaff'   => User::isStaff() || User::isAdmin(),
                'isAdmin'   => User::isAdmin() || Main::getLoginUserInfo('logonName') == 'aichenk',
                'nav'       => XhsysTree::createNav(),
                'power'     => [
                    'secretKey' => UserPower::checkUserPower('Person_SecretKey'),
                    'appDown'   => UserPower::checkUserPower('Person_AppDown'),
                ]
            ));
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 用户注销，清除所有session记录并返回主页面
     *
     * create by ck 20160301
     */
    public function signOutAction()
    {
        $this->view->disable();
        $this->session->destroy();                                      //销毁session
        return $this->response->redirect();
    }

    /**
     * 404页面
     *
     * create by ck 20160329
     */
    public function notFoundAction()
    {
        $this->tag->setTitle('404');
        $this->response->setStatusCode(404, 'Not Found');
        if ($this->request->isAjax()) {
            return $this->response->setJsonContent(['error' => 'Page Not Found']);
        }
        return $this->view->pick('index/404');
    }

    /**
     * 检查密码是否正确
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170809
     */
    public function checkPasswordAction()
    {
        $userId = Main::getLoginUserInfo('userId');
        $oldPwd = $this->request->getPost('oldPwd', 'string');
        if (!$userId) {
            return $this->sendErrorResponse(500, '无法修改！', '当前为未登录状态！');
        }
        if (!$oldPwd) {
            return $this->sendErrorResponse(400, '密码不能为空！');
        }
        $user = XhsysUser::findFirst($userId);
        if (!$user) {
            return $this->sendErrorResponse(500, '找不到用户信息！');
        }
        if (strtoupper($user->sLogonPwd) != strtoupper(md5($oldPwd))) {
            return $this->sendErrorResponse(400, '密码错误！');
        }
        return $this->sendSuccessResponse('密码验证通过！');
    }

    /**
     * 修改登陆用户密码，成功则清空session
     *
     * create by ck 20161104
     * modify by ck 20170809    更改返回结构
     */
    public function changeSelfPwdAction()
    {
        $userId = Main::getLoginUserInfo('userId');
        $oldPwd = $this->request->getPost('oldPwd', 'string');
        $newPwd = $this->request->getPost('newPwd', 'string');
        if (!$userId) {
            return $this->sendErrorResponse(500, '无法修改', '当前为未登录状态！');
        }
        if (!$oldPwd || !$newPwd) {
            return $this->sendErrorResponse(400, '参数不完整');
        }
        if (is_numeric($newPwd) || strlen($newPwd) < 8) {
            return $this->sendErrorResponse(400, '密码至少8位，且不能为纯数字');
        }
        try {
            User::setPassword([$userId], $newPwd);
            return $this->sendSuccessResponse('密码修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }

//        $user = XhsysUser::findFirst($userId);
//        if (!$user){
//            return $this->sendErrorResponse(500, '找不到用户信息！');
//        }
//        if (strtoupper($user->sLogonPwd) != strtoupper(md5($oldPwd))){
//            return $this->sendErrorResponse(400, '原密码错误！');
//        }
//        $user->sLogonPwd = strtoupper(md5($newPwd));
//        if (!$user->save()){
//            return $this->sendErrorResponse(500, '修改失败！', '数据库保存失败！');
//        }
//        return $this->sendSuccessResponse('密码修改成功！');
    }

    /**
     * 获取开发者密钥
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170824
     * modify by ck 20170827    适配安卓算法，更改为最多3个密钥
     * modify by ck 20170830    上下午截取BUG修复
     * modify by ck 20180529    更改为二维码
     * modify by ck 20181011    添加新刷机码
     */
    public function getSecretKeyAction()
    {
        if (!User::isLogin()) {
            return $this->sendErrorResponse(400, '未登陆，无法获取');
        }
        if (!UserPower::checkUserPower('Person_SecretKey')) {
            return $this->sendErrorResponse(403, '无开发密钥权限');
        }
        $oldKey = Main::getSecretKey();
        return $this->sendJsonResponse([
            'login' => Tool::getQRBase64Uri(json_encode(['password' => $oldKey, 'currentId' => User::getId()])),
            'brush' => Tool::getQRBase64Uri(
                json_encode(['account' => Main::getSecretKey(true), 'currentId' => User::getId()])
            ),
            'brushOld' => Tool::getQRBase64Uri(json_encode(['account' => $oldKey, 'currentId' => User::getId()])),
            'hour'  => date('G')
        ]);

//        $time  = time();
//        $keys  = [];
//        $year  = date('Y', $time);
//        $month = date('n', $time);
//        $day   = date('j', $time);
//        $hour  = date('G', $time);
//        for ($i = 0; $i < 3; $i++) {
//            if ($hour >= 24) break;
//            $key = sprintf('*#xuehai%d&zhitongyun%d$100fen%d@%d#*', $year, $month, $day, $hour);
//            $key = md5(base64_encode($key) . "\n");
//            $key = substr($key, $hour >= 12 ? 0 : 16, 16);
//            $keys[$hour] = $key;
//            $hour++;
//        }
//        return $this->sendJsonResponse(['time' => date('Y-m-d H:i:s', $time), 'keys' => $keys]);
    }

    /**
     * 检查是否需要填写问卷
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180408
     */
    public function checkSurveyAction()
    {
        if (!User::isLogin()) {
            return $this->sendErrorResponse(400, '未登陆，无法获取');
        }
        try {
            $survey = XhaskSurvey::getStaffSurvey();
            if (!$survey) {
                throw new \Exception('无问卷');
            }
            return $this->sendJsonResponse($survey);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), null, false);
        }
    }


    /**
     * 主界面锁定，清除session并返回用户ID
     *
     * create by ck 20160329
     */
//    public function lockScreenAction()
//    {
//        $this->view->disable();
//        echo Main::getLoginUserInfo('userId');
//        $this->session->destroy();                                      //销毁session
//    }

    /**
     * 主界面锁定，密码正确则设置session并返回标识
     *
     * create by ck 20160329
     */
//    public function unLockScreenAction()
//    {
//        $this->view->disable();
//        $userId     = $this->request->getPost('UserId');
//        $password   = $this->request->getPost('Password');
//        $user = XhsysUser::searchUserForLogin(null, $password, $userId);
//        $user or die('fail');
//        $this->session->set('auth', [
//            'userId'    =>  $user->iUserId,
//            'logonName' =>  $user->sLogonName,
//            'userName'  =>  $user->sUserName,
//            'userType'  =>  $user->iUserType,
//        ]);
//        echo 'success';
//    }


    /**
     * 链接到课程录入平台
     *
     * create by ck 20160803
     */
//    public function jumpResourcePageAction()
//    {
//        $this->view->pick('index/jumpResourcePage');
//        $authLogin = new \Helpers\AuthLogin('xh_webManage');
//        $url = $authLogin->runLinkstring(
//            'http://zt.yunzuoye.net:84/apps/course/resource/web/index/authlogin?',
//            ['userid' => Main::getLoginUserInfo('userId')]
//        );
//        $this->view->setVar('url', $url);
//    }

    /**
     * 注册在线
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180814
     */
    public function keepAliveAction()
    {
        $title  = $this->request->getPost('title', 'string');
        $url    = $this->request->getPost('url', 'string');
        $userId = User::getId();
        if (!$userId) {
            return $this->sendErrorResponse(403, '未登录', '', false);
        }
        try {
            $obj = UserOnline::findFirst($userId);
            if (!$obj) {
                $obj = new UserOnline(['userId' => $userId]);
            }
            $obj->logonName = Main::getLoginUserInfo('logonName');
            $obj->userName  = Main::getLoginUserInfo('userName');
            $obj->pageTitle = $title;
            $obj->pageUrl   = $url;
            if (!$obj->save()) {
                throw new \Exception($obj->getMessages()[0]);
            }
            return $this->sendSuccessResponse('success', false);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }
}

